﻿package net.wangit.sms;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.smslib.IOutboundMessageNotification;
import org.smslib.OutboundMessage;
import org.smslib.Service;
import org.smslib.modem.SerialModemGateway;

public class SMSSender {
	public class OutboundNotification implements IOutboundMessageNotification {
		public void process(String gatewayId, OutboundMessage msg) {
			SMSSender.log.info((new StringBuilder("发送状态: ")).append(gatewayId)
					.toString());
		}
	}

	private static final Log log = LogFactory
			.getLog(net.wangit.sms.SMSSender.class);
	private static Service srv = null;
	private static boolean start = false;

	public SMSSender() {
	}

	private boolean isStart() {
		if (!start)
			try {
				srv = new Service();
				SerialModemGateway gateway = new SerialModemGateway(SMSSettings
						.getName(), SMSSettings.getPort(), SMSSettings
						.getBaud(), SMSSettings.getProduct(), SMSSettings
						.getModel());
				gateway.setInbound(true);
				gateway.setOutbound(true);
				gateway.setSimPin("0000");
				srv
						.setOutboundMessageNotification(new IOutboundMessageNotification() {
							public void process(String gatewayId,
									OutboundMessage msg) {
								SMSSender.log
										.info((new StringBuilder("发送状态: "))
												.append(gatewayId).toString());
							}
						});
				srv.addGateway(gateway);
				System.out.println("start: 1");
				srv.startService();
				System.out.println("startService: ");
				log.info("--------------------------------");
				log.info("GSM Modem信息:");
				log.info((new StringBuilder("  厂家: ")).append(
						gateway.getManufacturer()).toString());
				log.info((new StringBuilder("  型号: ")).append(
						gateway.getModel()).toString());
				log.info((new StringBuilder("  序列号: ")).append(
						gateway.getSerialNo()).toString());
				log.info((new StringBuilder("  SIM IMSI: ")).append(
						gateway.getImsi()).toString());
				log.info((new StringBuilder("  信号强度: ")).append(
						gateway.getSignalLevel()).append("%").toString());
				log.info((new StringBuilder("  电池容量: ")).append(
						gateway.getBatteryLevel()).append("%").toString());
				log.info("--------------------------------");
				start = true;
			} catch (Exception e) {
				start = false;
				log.error("SMSModem not ready", e);
			}
		return start;
	}

	public boolean send(String number, String content) throws Exception {
		if (isStart()) {
			OutboundMessage msg = new OutboundMessage(number, content);
			msg.setEncoding(org.smslib.Message.MessageEncodings.ENCUCS2);
			srv.sendMessage(msg);
			return true;
		} else {
			return false;
		}
	}

}
